import router from '@/router'
import { getToken } from './utils/auth.js'
import { Message } from 'element-ui';
import store from './store/index.js';

const whiteList = ['/404', '/login']
router.beforeEach(async (to, from, next) => {
    const Token = getToken()
    //判断是否存在token
    if (Token) {
        // 存在
        const userInfo = store.getters.userInfo
        if (!userInfo.username) {
            const userInfo = await store.dispatch('user/getUserInfo')
            const newRoutes = await store.dispatch(
                'permission/setRoutes',
                userInfo.roles.menus
            )
            router.addRoutes([...newRoutes,
            { path: '*', redirect: '/404', hidden: true }])

            next(to.path)
        }
        // 判断是否是登陆页
        if (to.path == '/login') {
            Message.warning('您已经登陆过了哦~')
            next('/')
        } else {
            next()
        }
    } else {
        const bool = whiteList.includes(to.path)
        if (bool) {
            next()
        } else {
            Message.warning('您还没有登陆哦~')
            next(`/login?_redirece=${to.path}`)
        }
    }
})